package com.utils;

import java.io.IOException;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

import com.conf.MenuEnum;
import com.log.LogMonitorFactroy;
import com.msg.ShowMessage;

/**
 * Title: <br>
 * Description:  <br>
 * Copyright: WangGuangya<br>
 * Company: WangGuangya<br>
 * @author WangGuangya
 * @version 1.0
 * @date 2018-02-23
 */

public class ShellUtil {

	private Connection conn;
	
	private String ip = "";
	private String user = "";
	private String pwd = "";
	
	private static final int TIME_OUT = 1000 * 30 * 60;
    
    /**
     * 构造函数 
     * @param ip 
     * @param usr 
     * @param ps 
     */ 
    public ShellUtil(String ip, String usr, String ps) { 
        this.ip = ip; 
        this.user = usr; 
        this.pwd = ps; 
    } 
    
	/** 
     * 登录 
     * 
     * @return 
     * @throws IOException 
     */ 
    private boolean login() throws IOException { 
        conn = new Connection(ip); 
        conn.connect();
        return conn.authenticateWithPassword(user, pwd); 
    } 
    
    /** 
     * 执行脚本 并打印日志
     * @param cmds 
     * @param printLog
     * @return 
     * @throws Exception 
     */ 
    public int exec(MenuEnum menuEnum) {
        int ret = -1; 
        try { 
            if (login()) { 
                // Open a new {@link Session} on this connection 
                Session session = conn.openSession(); 
                // Execute a command on the remote machine. 
                session.execCommand(menuEnum.command); 
                
                WatchThread wt = new WatchThread(session.getStdout());
                wt.start();
    			
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); 
                wt.setOver(true);
                ret = session.getExitStatus();
                session.close();
            } else { 
            	LogMonitorFactroy.newInstance().append("登录远程机器失败" + ip);
                throw new Exception("登录远程机器失败" + ip); 
            } 
        } catch (Exception e) {
        	e.printStackTrace();
    	} finally {
            if (conn != null) { 
                conn.close(); 
            } 
        } 
        if (ret != 1) {
			LogMonitorFactroy.newInstance().append("命令：" + menuEnum.command + "执行成功");
		} else {
			LogMonitorFactroy.newInstance().append("命令：" + menuEnum.command + "执行失败");
		}
        return ret;
    }
    
    /** 
     * 执行脚本 并打印日志
     * @param cmds 
     * @param printLog
     * @return 
     * @throws Exception 
     */ 
    public int exec(String cmds, ShowMessage msg) {
    	msg.append("执行机器" + this.ip + "上的命令:" + cmds);
    	
        int ret = -1; 
        try { 
            if (login()) { 
                // Open a new {@link Session} on this connection 
                Session session = conn.openSession(); 
                // Execute a command on the remote machine. 
                session.execCommand(cmds); 
                
                WatchThread wt = new WatchThread(session.getStdout());
                wt.start();
    			
                session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); 
                wt.setOver(true);
                ret = session.getExitStatus();
                session.close();
            } else { 
            	msg.append("登录远程机器失败" + ip);
                throw new Exception("登录远程机器失败" + ip); 
            } 
        } catch (Exception e) {
        	e.printStackTrace();
    	} finally {
            if (conn != null) { 
                conn.close(); 
            } 
        } 
        if (ret != 1) {
			msg.append("命令：" + cmds + "执行成功");
		} else {
			msg.append("命令：" + cmds + "执行失败");
		}
        return ret;
    }

    /** 
     * 执行脚本 并打印日志
     * @param cmds 
     * @param printLog
     * @return 
     * @throws Exception 
     */ 
    public int exec(String[] cmds, ShowMessage msg) throws Exception { 
//    	System.out.println("执行机器" + this.ip + "上的命令:" + cmds);
        int ret = -1;
        Process process = Runtime.getRuntime().exec(cmds);
        
        WatchThread wt = new WatchThread(process.getInputStream());
        wt.start();
        
		process.waitFor();
		wt.setOver(false);
        ret = process.exitValue();
        process.destroy();
        
        return ret;
    } 
}
